﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace VlcPlayer
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Text = AppResources.Add;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).Text = AppResources.SendReport;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).Text = AppResources.Rate;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).Text = AppResources.Help;
            ((ApplicationBarMenuItem) ApplicationBar.MenuItems[0]).Text = AppResources.About;
        }

        private List<VlcSettings> _vlcServers;
        private bool _remoteDlgChecked;

        private List<VlcSettings> VlcServers
        {
            get { return _vlcServers; }
            set { _vlcServers = value; }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            
            if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue("Servers",out _vlcServers) || _vlcServers==null || _vlcServers.Count==0)
            {
                VlcServers= new List<VlcSettings>(){new VlcSettings()};
                IsolatedStorageSettings.ApplicationSettings.Clear();
                IsolatedStorageSettings.ApplicationSettings["Servers"]=VlcServers;
                IsolatedStorageSettings.ApplicationSettings.Save();

                NavigationService.Navigate(new Uri("/Settings.xaml?id=0", UriKind.Relative));
            }

            ServerList.DataContext = null;
            ServerList.DataContext = VlcServers;

            if (!_remoteDlgChecked)
            {
                _remoteDlgChecked = true;
                RemoteDialog.ShowIfAvailableAsync(
                    "http://www.casa-del-stifler.de/AppContent/VlcPlayer/RemoteDialog.xaml", this);
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            IsolatedStorageSettings.ApplicationSettings["Servers"] = VlcServers;
            IsolatedStorageSettings.ApplicationSettings.Save();
        }


        private void ServerList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ServerList.SelectedItem != null)
            {
                var vlc=(VlcSettings) ServerList.SelectedItem;
                ServerList.SelectedItem = null;

                if (string.IsNullOrWhiteSpace(vlc.Host) || vlc.Port < 1)
                {
                    NavigationService.Navigate(new Uri("/Settings.xaml?id=" + VlcServers.IndexOf(vlc), UriKind.Relative));
                    return;
                }

                NavigationService.Navigate(new Uri("/Browser.xaml?svId=" + this.VlcServers.IndexOf(vlc) + "&src=http://" + vlc.Host + ":" + vlc.Port, UriKind.Relative));
            }
        }

        private void SendReport_Click(object sender, EventArgs e)
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                try
                {
                    string errorLog = "";

                    if (file.FileExists("error_log"))
                    {
                        using (StreamReader reader = new StreamReader(file.OpenFile("error_log", FileMode.Open, FileAccess.Read)))
                        {
                            errorLog = reader.ReadToEnd();
                        }
                    }
                    
                    EmailComposeTask em = new EmailComposeTask();
                    em.To = AppResources.EMailAddress;
                    em.Subject = "Error Report: " + AppResources.AppTitle;
                    em.Body = "Optional: add your message" + Environment.NewLine + Environment.NewLine + Environment.NewLine + errorLog;
                    em.Show();

                    file.DeleteFile("error_log");
                }
                catch (IsolatedStorageException ex) { }
            }
        }

        private void EditClick(object sender, RoutedEventArgs e)
        {
            var btn = (Button) sender;
            var sv =(VlcSettings)btn.DataContext;
            var idx=VlcServers.IndexOf(sv);

            NavigationService.Navigate(new Uri("/Settings.xaml?id=" + idx, UriKind.Relative));
        }

        private void AddClick(object sender, EventArgs e)
        {
            var server = new VlcSettings();
            VlcServers.Add(server);
            IsolatedStorageSettings.ApplicationSettings["Servers"] = VlcServers;
            IsolatedStorageSettings.ApplicationSettings.Save();
            var idx = VlcServers.IndexOf(server);

            NavigationService.Navigate(new Uri("/Settings.xaml?id="+idx, UriKind.Relative));
        }

        private void RateClick(object sender, EventArgs e)
        {
            var ret = MessageBox.Show(AppResources.RateText, AppResources.Rate, MessageBoxButton.OKCancel);
            if (ret == MessageBoxResult.OK)
            {
                MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                marketplaceReviewTask.Show();
            }
        }

        private void HelpClick(object sender, EventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri(AppResources.DocumentationURL, UriKind.Absolute);
            webBrowserTask.Show();
            //NavigationService.Navigate(new Uri("/Help.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/YourLastAboutDialog;component/AboutPage.xaml", UriKind.Relative));
        }
    }
}